package com.sangmo.fts;

import com.sangmo.boot.framework.cache.CacheAspect;
import com.sangmo.boot.framework.cache.ICache;
import com.sangmo.boot.framework.cache.local.LocalCache;
import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.boot.framework.common.utils.ApplicationUtils;
import com.sangmo.boot.framework.event.ByThreadEventDispatcher;
import com.sangmo.boot.framework.event.IEventDispatcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.MultipartConfigElement;
import java.io.File;


@SpringBootApplication
@ImportResource("classpath:spring/applicationContext*.xml")
@ComponentScan({"com.sangmo"})
@PropertySource(value="classpath:config/application.properties",encoding = "UTF-8", ignoreResourceNotFound = true)
public class ServerApplication {

    public static void main(String[] args) {
        SpringApplication APP = new SpringApplication(ServerApplication.class);
        APP.setBannerMode(Banner.Mode.OFF);
        APP.setLogStartupInfo(false);
        ApplicationUtils.CONTEXT = APP.run(args);
    }

    @Bean
    public IEventDispatcher eventDispatcher() {
        ByThreadEventDispatcher byThreadEventDispatcher = new ByThreadEventDispatcher();
        return byThreadEventDispatcher;
    }

    @Bean(name = "multipartResolver")
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setDefaultEncoding("UTF-8");
        resolver.setMaxUploadSize(1024 * 1024 * 100);
        resolver.setMaxInMemorySize(-1);
        return resolver;
    }

    /**
     * 配置上传文件临时目录
     *
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        String path = System.getProperty("user.dir");
        String location = path + "/files";
        File tmpFile = new File(location);
        // 如果临时目录不存在则创建
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        // 明确指定上传文件的临时目录
        factory.setLocation(location);
        return factory.createMultipartConfig();
    }
}
